﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FrbaBus.Core;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

namespace FrbaBus.Abm_Micro
{
    public partial class ModificarMicro2 : Form
    {
        public ModificarMicro2()
        {
            InitializeComponent();
        }
      //  bool intervaloServicio = true;
        private ModificarMicro parent = null;
        public DateTime bajaDefinitiva;
        public DateTime fechaDeAlta;
        public string fechaDeAltaHora;
        public string bajaDefinitivaHora;
        public string butacasinsert;
        public string butacasupdate;
        public string butacasupdate2;
        
        public DateTime to;
        public string toHora;
        public int cantButacasOnLoad;

        public DateTime from;
        public string fromHora;
        public bool especificarButacas = false;
        public int cantButacasPrevias = 0;


        private void textchanged(object sender, KeyPressEventArgs e)
        {
            int i = e.KeyChar;
            if (i >= 48 && i <= 57 || i == 8 || i == 13)
            {
            }
            else
            {
                MessageBox.Show("Solo están permitidos caracteres numéricos.");
                e.Handled = true;
            }
        }
        

        public ModificarMicro2 (Form callingForm)
        {
            parent = callingForm as ModificarMicro;

            InitializeComponent();
        }

        private void ModificarMicro2_Load(object sender, EventArgs e)
        {
            dateTimePicker2.MinDate = Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"]);
            dateTimePicker3.MinDate = Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"]);
            
            string patente = String.Copy(this.parent.Row.Cells[0].Value.ToString());
            comboBox1.Items.Clear();
            comboBox1.Text = "";
            DBManager db = new DBManager();
            SqlCommand consulta = new SqlCommand("select Tipo_Servicio from ALL_IN.Tipo_Servicio");
            SQLResponse r = db.executeQuery(consulta);
            SqlCommand consulta2 = new SqlCommand("select count (*) from ALL_IN.Tipo_Servicio");
            SQLResponse r2 = db.executeQuery(consulta2);
            SqlCommand consulta3 = new SqlCommand("select COUNT(*) from ALL_IN.Butaca where Patente= '" + patente + "'");
            SQLResponse r3 = db.executeQuery(consulta3);
            int valor3 = (int)r3.result.Rows[0][0];
            int valor = (int)r2.result.Rows[0][0];
            for (int i = 0; i < valor; i++)
            {
                comboBox1.Items.Add(r.result.Rows[i][0].ToString());
            }
            textBox1.Text = valor3.ToString();
            numericUpDown2.Value = Convert.ToInt16(valor3);
            numericUpDown2.Minimum = Convert.ToInt16(valor3);
            cantButacasOnLoad = Convert.ToInt16(valor3);

            

                textBox10.Text = String.Copy(this.parent.Row.Cells[0].Value.ToString());
                dateTimePicker1.Text = String.Copy(this.parent.Row.Cells[1].Value.ToString());
                textBox3.Text = String.Copy(this.parent.Row.Cells[2].Value.ToString());              
                textBox7.Text = String.Copy(this.parent.Row.Cells[3].Value.ToString());
                comboBox2.Text = String.Copy(this.parent.Row.Cells[4].Value.ToString());
                comboBox2.Text = String.Copy(this.parent.Row.Cells[4].Value.ToString());
                comboBox1.Text = String.Copy(this.parent.Row.Cells[5].Value.ToString());
                textBox4.Text = String.Copy(this.parent.Row.Cells[5].Value.ToString());
                textBox2.Text = String.Copy(this.parent.Row.Cells[8].Value.ToString());
                numericUpDown1.Value = Convert.ToInt16(textBox2.Text);
                numericUpDown1.Minimum = Convert.ToInt16(textBox2.Text);
                string bajaServicio = string.Copy(this.parent.Row.Cells[6].Value.ToString());
                dateTimePicker2.Text = String.Copy(this.parent.Row.Cells[9].Value.ToString());
                dateTimePicker3.Text = String.Copy(this.parent.Row.Cells[10].Value.ToString());
                               
                dateTimePicker4.Text = String.Copy(this.parent.Row.Cells[11].Value.ToString());
                SqlCommand consulta5 = new SqlCommand("select Distinct Marca from ALL_IN.Marca");
                SQLResponse r5 = db.executeQuery(consulta5);
                SqlCommand consulta6 = new SqlCommand("select count (Distinct Marca) from ALL_IN.Marca");
                SQLResponse r6 = db.executeQuery(consulta6);
                valor = (int)r6.result.Rows[0][0];
                for (int i = 0; i < valor; i++)
                {
                    comboBox2.Items.Add(r5.result.Rows[i][0].ToString());
                }

                db.desconectar();      

                



            

        }


        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                groupBox1.Visible = true;
                dateTimePicker2.Enabled = true;
                dateTimePicker3.Enabled = true;
            }
            else
            {
                groupBox1.Visible = false;
            }

                }

        public class Foo
        {
            public static int validacion = 1;
            public static bool intervaloServicio = false;
        }

        public string query = null;
        private void button1_Click_1(object sender, EventArgs e)
        {


            
            Foo.validacion = 1;
            // VALIDAR QUE HAY DATOS EN TODOS LOS CAMPOS
            
            if (comboBox2.Text == "" || textBox1.Text == "" || comboBox1.Text == "" || textBox2.Text == "" || textBox3.Text == ""
                || textBox7.Text == "" || textBox10.Text == "" )
            {
                MessageBox.Show("Todos los campos deben ser completados");
                Foo.validacion = 0;
            }
            // VALIDAR FECHA BAJA DEFINITIVA
            DBManager db22 = new DBManager();
            SqlCommand consulta22 = new SqlCommand("SELECT ALL_IN.existeViajesActivos('" + textBox10.Text + "', '" + (dateTimePicker4.Value.ToString("yyyy-MM-dd") + " 00:00:00.000") + "')");
            SQLResponse r22 = db22.executeQuery(consulta22);
            bool valor2 = (bool)r22.result.Rows[0][0];
            if (valor2 == true)
            {
                DBManager db44 = new DBManager();
                SqlCommand consulta44 = new SqlCommand("select  MAX (Fecha_Salida) from ALL_IN.viajesActivos where patente = '" + textBox10.Text.ToString() + "'");
                SQLResponse r44 = db44.executeQuery(consulta44);
                DateTime fechita = Convert.ToDateTime(r44.result.Rows[0][0]);


                MessageBox.Show("La fecha de baja debe ser posterior al ultimo viaje programado (" + fechita.ToString("yyyy-MM-dd") + ")");
                Foo.validacion = 0;
            }
            // VALIDAR FECHA ALTA
            DBManager db23 = new DBManager();

            
            SqlCommand consulta23 = new SqlCommand("SELECT ALL_IN.existeViajeMasAntiguo('" + textBox10.Text + "', '" + (dateTimePicker1.Value.ToString("yyyy-MM-dd") + " 00:00:00.000") + "')");
            SQLResponse r23 = db23.executeQuery(consulta23);
            bool valor3 = (bool)r23.result.Rows[0][0];
            
            if (valor3 == true)
            {
                DBManager db44 = new DBManager();
                SqlCommand consulta44 = new SqlCommand("select  MIN (Fecha_Salida) from ALL_IN.Viaje where patente = '" + textBox10.Text.ToString() + "'");
                SQLResponse r44 = db44.executeQuery(consulta44);
                DateTime fechita = Convert.ToDateTime(r44.result.Rows[0][0]);

                MessageBox.Show("La fecha de alta no puede ser posterior al viaje mas antiguo que registra el micro(" + fechita.ToString("yyyy-MM-dd") + ")");
                Foo.validacion = 0;
            }




            if (dateTimePicker4.Value.Date.CompareTo(dateTimePicker1.Value.Date) < 0)
            {
                MessageBox.Show("Fecha baja definitiva debe ser mayor a fecha de alta");
                Foo.validacion = 0;
            }



            
            if ( Foo.validacion == 1 )
            {
                DBManager db = new DBManager();
                fechaDeAlta = dateTimePicker1.Value;
                fechaDeAltaHora = fechaDeAlta.ToString("yyyy-MM-dd");
                fechaDeAltaHora = fechaDeAltaHora + " 00:00:00.000";
                bajaDefinitiva = dateTimePicker4.Value;
                bajaDefinitivaHora = bajaDefinitiva.ToString("yyyy-MM-dd");
                bajaDefinitivaHora = bajaDefinitivaHora + " 00:00:00.000";
                //string marca = comboBox2.Text;
                SqlCommand existemarca = new SqlCommand("select ALL_IN.existeMarca ('" + comboBox2.Text.ToString() + "')");
                SQLResponse IDmarca = db.executeQuery(existemarca);
                if (IDmarca.result.Rows[0][0].ToString() == "False")
                {
                    SqlCommand consulta9 = new SqlCommand("insert ALL_IN.Marca(marca) values('" + comboBox2.Text.ToString() + "')");
                    db.executeQuery(consulta9);
                }

                SqlCommand MarcaID = new SqlCommand("select ID_Marca from ALL_IN.Marca where Marca='" + comboBox2.Text.ToString() + "'");
                SQLResponse r10 = db.executeQuery(MarcaID);

                query = "update ALL_IN.Micros SET Modelo='" + textBox7.Text + "',Marca='" + r10.result.Rows[0][0].ToString() +
                    "',Fecha_Alta='" + fechaDeAltaHora + 
                "',Tipo_Servicio='" + comboBox1.Text+ "', Cantidad_Kg='" + numericUpDown1.Value + "',Fecha_Baja_Definitiva='" + bajaDefinitivaHora + "'";
                if (checkBox1.Checked == true)
                {
                    to = dateTimePicker3.Value;
                    toHora = to.ToString("yyyy-MM-dd");
                    toHora = toHora + " 00:00:00.000";

                    from = dateTimePicker2.Value;
                    fromHora = from.ToString("yyyy-MM-dd");
                    fromHora = fromHora + " 00:00:00.000";

                    query = query + ",[Fecha_Fuera_de_Servicio]='" + fromHora + "',[Fecha_Reinicio_Servicio]='" +
                        toHora + "'";
                }
                if (cantButacasOnLoad != numericUpDown2.Value && especificarButacas == false)
                {
                    SqlCommand consultaX = new SqlCommand("exec ALL_IN.agregarButacas @patente = '" + textBox10.Text.ToString() + "', @cantButacas= '" + (numericUpDown2.Value - cantButacasOnLoad) + "'");
                    db.executeQuery(consultaX);
                }
                if (especificarButacas == true)
                {

                    //utilizar el string del hijo para la modificacion de las butacas
                    //el nombre de la variable es s1

                    if (butacasupdate != null && butacasupdate2 != null)
                    {

                        SqlCommand consultaK = new SqlCommand(butacasupdate + "where Patente='" + textBox10.Text + "'" + butacasupdate2);
                        SQLResponse rK = db.executeQuery(consultaK);
                    }

                    if (butacasinsert != null)
                    {
                        string butacas2 = butacasinsert.Replace("(", "('" + textBox10.Text + "',");
                        SqlCommand consultaZ = new SqlCommand(" insert into ALL_IN.Butaca(Patente,ID_Butaca,Tipo_Butaca,Piso) values"
                            + butacas2);
                        db.executeQuery(consultaZ);
                    }
                    db.desconectar();
                }
               



                

                query = query + " WHERE Patente='" + textBox10.Text + "'";
                SqlCommand consulta = new SqlCommand(query);
                SQLResponse r = db.executeQuery(consulta);
                MessageBox.Show(" Se han actualzado los datos");
                this.Close();
            }
        }


        private void dateTimePicker4_ValueChanged(object sender, EventArgs e)
        {
            dateTimePicker4.MinDate = Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"]);
       
        }

        private void dateTimePicker3_ValueChanged(object sender, EventArgs e)
        {
            Foo.intervaloServicio = true;
        }

        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {
            Foo.intervaloServicio = true;
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            // La fecha de alta no puede ser posterior al viaje mas antiguo que registra el micro.

        }

        private void button4_Click(object sender, EventArgs e)
        {
            DBManager db = new DBManager();
           /* SqlCommand consultaJ = new SqlCommand("select COUNT(DISTINCT ID_Butaca) from ALL_IN.Disponibilidad_Butaca d where d.Mic_Patente = '" +
               textBox10.Text + "' AND Fecha_Salida > (select * from ALL_IN.Fecha_Actual)" +
            "AND NOT EXISTS ( SELECT * FROM ALL_IN.Cancelacion c WHERE c.Nro_Pasaje = d.Nro_Pasaje )");
            SQLResponse rJ = db.executeQuery(consultaJ);
            int valor2 = (int)rJ.result.Rows[0][0];
            if (valor2 > 0)
            {
                MessageBox.Show("No pueden ser modificada la distribucion de butacas, el micro posee viajes vendidos en el futuro");
            }
            else
            {*/
                Abm_Micro.Distribucion_de_Butacas frm = new Abm_Micro.Distribucion_de_Butacas(this, false);
                frm.ShowDialog(this);
                numericUpDown2.ReadOnly = true;
                numericUpDown2.Enabled = false;
        }









    }


 
}

